//
//  HomeController.swift
//  SinaBlog
//
//  Created by 有何不可 on 15/12/30.
//  Copyright © 2015年 有何不可. All rights reserved.
//

import UIKit
import AFNetworking
import SDWebImage
import SVProgressHUD


let cellResuseIdentifier = "cell"

class HomeController: BaseTableViewController {
    
    lazy var homeViewModel = HomeViewModel()
    
    private lazy var upPullView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        if !islogin {
            vision?.setInit(nil, text: "登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过")
        } else {
            tableView.registerClass(HomeCell.self, forCellReuseIdentifier: cellResuseIdentifier)
            
            tableView.rowHeight = UITableViewAutomaticDimension
            
            tableView.estimatedRowHeight = 200
            
            refreshControl = PullingRefreshControl()
            
            getData()
            
            tableView.tableFooterView = upPullView
            
            refreshControl?.beginRefreshing()
            
            refreshControl?.addTarget(self, action: "repeatLoadData", forControlEvents: UIControlEvents.ValueChanged)
        }
    }
    
    @objc private func repeatLoadData() {
        
        getData()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    private func getData() {
//        SVProgressHUD.show()
       var sinse_id = homeViewModel.list.first?.statuse?.id ?? 0
       var max_id = 0
        
        if upPullView.isAnimating() {
            //给max_id减一是为了 让返回的数据不会返回他本身,只返回币max_id - 1还小的数据
            max_id = (homeViewModel.list.last?.statuse?.id ?? 0) - 1
            sinse_id = 0
        }
        
        homeViewModel.getData(sinse_id, max_id: max_id, success: { (count) -> () in
            
            self.tableView.reloadData()
            //下拉刷新结束
            self.refreshControl?.endRefreshing()
            //根据是否执行上拉的动画来判断,是否弹提示框
            if !self.upPullView.isAnimating() {
            self.remindCount(count)
            }
            //上拉更多结束动画
            self.upPullView.stopAnimating()
//            SVProgressHUD.dismiss()
            
            }) { (error) -> () in
                print(error)
                
//            SVProgressHUD.dismiss()
        }
    }
    
    private func remindCount(count: Int) {
        
        let height: CGFloat = 44
        
        let remindLal: UILabel = UILabel()
        
        remindLal.frame = CGRectMake(0, CGFloat(64) - height, kScreenWidth, height)
        
        remindLal.backgroundColor = UIColor.orangeColor()
        
        remindLal.textAlignment = NSTextAlignment.Center
        
        remindLal.textColor = UIColor.lightTextColor()
        
        if count == 0 {
            
            remindLal.text = "暂无更新"
        } else {
            
            remindLal.text = "更新了\(count)条微博"
        }
        
        navigationController?.view.insertSubview(remindLal, belowSubview: navigationController!.navigationBar)
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            remindLal.transform = CGAffineTransformMakeTranslation(0, height)
            }) { (_) -> Void in
                
                UIView.animateWithDuration(3, animations: { () -> Void in
                    
                    remindLal.transform = CGAffineTransformIdentity
                    
                    remindLal.alpha = 0.2
                    
                    }, completion: { (_) -> Void in
                        
                    remindLal.removeFromSuperview()
                })
        }
    } 
}

extension HomeController {

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeViewModel.list.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(cellResuseIdentifier, forIndexPath: indexPath) as! HomeCell
        
        if indexPath.item == homeViewModel.list.count - 1 && !upPullView.isAnimating() {
            
            upPullView.startAnimating()
            
            getData()
        }
        
        let personalBlogViewModel = homeViewModel.list[indexPath.row]

        cell.personalBlogViewModel = personalBlogViewModel
        
        return cell
    }
    
}